#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import re, urllib
import datetime, time
import shutil

import sqlite3dbm

from generator import * 
from models import *
from paneo import *

import web
from sqlobject import *
sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)

#render
from web.contrib.template import render_mako

render = render_mako(   directories=[PANEO_ROOT+'/_cms/templates/'],
                        input_encoding='utf-8',
                        output_encoding='utf-8',
                        default_filters=["none_to_blank", "unicode"],
                        encoding_errors='replace', 
                        imports = RENDER_IMPORTS )

import math
import pickle
from datetime import datetime

class View:

    def __init__(self):
        self.cms = 'a_'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self , prefix , p = 1):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        dic.close()

        article = Articles.select(Articles.q.prefix == prefix).getOne(default=None)
        if not article :
            return web.notfound()

        art_p = PaneoPage()
        article_img = art_p.GetPageImageFields('art',prefix)
        img_alt = article.img
        if not img_alt :
            img_alt = {}

        rows = 10.0
        p = int(p)
        results = Posts.select( Posts.q.article == article ).orderBy('-id')
        posts = results[(p-1)*rows:rows*p]
        count = results.count()
        pages = int(math.ceil(count / rows))

        return render.articles(     
                                cms = self.cms,
                                scfg = scfg, 
                                mode = 'view',
                                prefix = prefix,
                                article = article,
                                article_img = article_img, 
                                img_alt = img_alt,
                                posts = posts,
                                count = count,
                                p = p,
                                pages = pages,
        )

    def POST( self , prefix , p = 1):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        dic.close()

        article = Articles.select(Articles.q.prefix == prefix).getOne(default=None)
        if not article :
            return web.notfound()

        i = web.input( CATEGORY = [] )

        #FIELD
        if i.HEADER == "" :
            article.header = article.title
        else:
            article.header = i.HEADER

        article.lead = i.LEAD
        article.description = i.DESCRIPTION
        article.keyword = i.KEYWORD

        #Share Text
        _context = {}
        for ii in range(1,6):
            _context['context%s'%ii] = i.get('CONTEXT%s'%ii,'')
        article.context = _context

        #Share IMAGES
        art_p = PaneoPage()
        art_p.PostPageImageFields('art',i,prefix)
        article.img = art_p.IMG 

        return self.GET( prefix, p )


class PostNew:
    def GET( self , prefix ):
        article = Articles.select(Articles.q.prefix == prefix).getOne(default=None)
        max = Posts.select( Posts.q.article == article ).count()
        if max is None:
            max = 1
        else:
            max = max + 1

        group = Groups.select(AND(Groups.q.articlestype == article.type , Groups.q.code == '0000')).getOne(default=None)
        category = Categories.select(AND(Categories.q.articlestype == article.type , Categories.q.code == '0000')).getOne(default=None)
        post = Posts(  
            article = article, 
            viewed = 0,
            slug = ("%s_%s" % (article.prefix,max)),
            key = "",
            title = u"%sの新規記事 タイトルを入力してください" % ( article.title ), 
            description = "",
            keyword = "",
            group = group,
            password = "",
            template = article.default_template,
            #date = DateTimeCol(notNone=1,default=DateTimeCol.now)
            #rawtext = UnicodeCol()
            #label1 = UnicodeCol()
            #label2 = UnicodeCol()
            #label3 = UnicodeCol()
            #viewed = BoolCol(notNone=1, default=True)
            #created = DateTimeCol(notNone=1,default=DateTimeCol.now)
        )
        post.addCategories(category)
        #post.syncUpdate()
        return web.seeother('http://' + web.ctx.host + '/paneo/articles/%s/' % prefix)

class PostEdit:

    def __init__(self):
        self.cms = 'a_'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self , prefix , id = None, art_mode = 'template'):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        dic.close()

        #sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)
        article = Articles.select(Articles.q.prefix == prefix).getOne(default=None)
        if not article :
            return web.notfound()

        post = Posts.select(Posts.q.id == id).getOne(default=None)
        if not post :
            return web.notfound()

        fields = post.fields
        if fields is None:
            fields = {}

        post_page = PaneoPage()
        post_page.TEMPLATE = post.template
        post_page.TEMPLATE_SYSTEM_USE = post.article.template_system_use
        post_page.VIEWED = post.viewed
        post_page.TITLE = post.title
        #post.LINK  = post.link
    
        html_fields = {} 
        html_file = post_page.GetPageTemplateFile(id,post=post)
        templates = post_page.GetPageTemplateNames(id,post)

        #CONTENTS
        if art_mode == 'contents':
            html_fields = post_page.GetPaneoTextFields('post',id,fields,post) 
        #IMAGES
        if art_mode == 'images':
            html_fields = post_page.GetPaneoImageFields('post',id,fields,post) 
        #AMAZON
        if art_mode == 'ecaws':
            html_fields = post_page.GetPaneoAmazonFields('post',id,fields,post) 

        return render.articles_post(     
                                cms = self.cms,
                                scfg = scfg, 
                                mode = 'edit',
                                prefix = prefix,
                                id = id,
                                art_mode = art_mode,
                                article = article,
                                post = post,
                                templates = templates,
                                html_file = html_file,
                                html_fields = html_fields,
                                page = post_page,
        )


    def POST( self , prefix , id = None, art_mode = 'template'):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        dic.close()

        #sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)
        article = Articles.select(Articles.q.prefix == prefix).getOne(default=None)
        if not article :
            return web.notfound()

        post = Posts.select(Posts.q.id == id).getOne(default=None)
        if not post :
            return web.notfound()

        i = web.input( CATEGORY = [] )

        #DELETE
        if i.has_key("CONTENTS_DELETE"):
            Posts.delete(post.id)
            return web.seeother("/paneo/articles/%s/" % prefix )

        post.viewed = int(i.VIEWED)
        post.slug = i.SLUG
        post.key = i.KEY
        post.title = i.TITLE
        post.header = i.HEADER
        post.lead = i.LEAD
        post.description = i.DESCRIPTION
        post.keyword = i.KEYWORD
        post.date = datetime.strptime(i.DATE + " 00:00:00", '%Y-%m-%d %H:%M:%S')
        post.password = i.PASSWORD
        post.updated = datetime.now() 
        #post.syncUpdate()

        fields = post.fields
        if fields is None:
            fields = {}
        post_page = PaneoPage()
        post_page.TEMPLATE = post.template,
        post_page.TEMPLATE_SYSTEM_USE = post.article.template_system_use,
        post_page.VIEWED = post.viewed,
        post_page.TITLE = post.title,

        ##TEMPLATE
        if art_mode == 'template':
            #TEMPLATE更新
            if post.template != i.TEMPLATE:
                post_page.PostPageChangeTemplateFile(id,i.TEMPLATE,post)
            else:
                if i.has_key("HTMLTEMPLATE"):
                    post_page.PostPageTemplateFile(id,i.HTMLTEMPLATE,post)
            post.template = i.TEMPLATE
            post.syncUpdate()
            return self.GET( prefix, id , art_mode )

        #GROUP
        if art_mode == 'category' and i.has_key('GROUP_COMMIT'):
            if i.G_CODE == "":
                web.ctx.MSG = u"GROUP CODEが未入力でです。"
                return self.GET( prefix, id , art_mode )

            if i.G_LABEL == "":
                web.ctx.MSG = u"GROUP名が未入力でです。"
                return self.GET( prefix, id , art_mode )

            group = Groups(
                        code = i.G_CODE,
                        parent = None,
                        label = i.G_LABEL,
                        articlestype = article.type, 
                        idx = 0,
            )

        #CATEGORY
        if art_mode == 'category' and i.has_key('CATEGORY_COMMIT'):

            if i.C_CODE == "":
                web.ctx.MSG = u"カテゴリーCODEが未入力でです。"
                return self.GET( prefix, id , art_mode )

            if i.C_LABEL == "":
                web.ctx.MSG = u"カテゴリー名が未入力でです。"
                return self.GET( prefix, id , art_mode )

            category = Categories(
                        code = i.C_CODE,
                        parent = None,
                        label = i.C_LABEL,
                        articlestype = article.type, 
                        idx = 0,
            )

        #GROUP and CATEGORY POST CHANGE
        if art_mode == 'category':
            #GROUP SET
            group = Groups.select(Groups.q.id == i.GROUP).getOne(default=None)
            if not group is None:
                post.group = group 
            #CATEGORY ADD
            for c in post.article.type.categories:
                post.removeCategories(c)
            for c in i.CATEGORY:
                category = Categories.select(Categories.q.id == c).getOne(default=None)
                if not category is None:
                    post.addCategories(category)

        #CONTENTS
        if art_mode == 'contents':
            post.fields = post_page.PostPaneoTextFields('post',id,fields,post)

        #IMAGES
        if art_mode == 'images':
            post.fields = post_page.PostPaneoImageFields('post',id,fields,post)

        #AMAZON
        if art_mode == 'ecaws':
            post.fields = post_page.PostPaneoAmazonFields('post',id,fields,post)

        post.syncUpdate()

        return self.GET( prefix, id , art_mode )


import csv, codecs, cStringIO

class TransView:

    def __init__(self):
        self.cms = 'a_'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def MakeCSVData( self, article ):
        post_page = PaneoPage()

        csv_heads = {}
        csv_heads["id"] = {'idx':1,'caption':u'ID番号'}
        csv_heads["slug"] = {'idx':2,'caption':u'ファイル名'}
        csv_heads["title"] = {'idx':3,'caption':u'タイトル'}
        csv_heads["header"] = {'idx':4,'caption':u'ヘッダー'}
        csv_heads["lead"] = {'idx':5,'caption':u'リード文'}
        csv_heads["description"] = {'idx':6,'caption':u'説明文'}

        #TEMPALTE FOLDER
        no = 7 
        tempdir = TEMPLATE_DIR + 'article_templateset/' + article.template_set + '/' 
        #MAKE FOLDER
        tmps = glob.glob( tempdir + '*.html')
        for f in tmps:
            file = codecs.open( f,"r","utf8")
            html = file.read()
            file.close()
            bs = post_page.GetTemplateToBeautifulSoupMakeCompile(html)
            for tag in bs.find_all(attrs={'data-paneo-name':True}):
                paneo_type = tag.get('data-paneo-type')
                paneo_name = tag.get('data-paneo-name')
                title = tag.get('title')
                if paneo_name and ( paneo_type == 'text' or paneo_type == 'textarea' ):
                    if not csv_heads.has_key( paneo_name ):
                        csv_heads[paneo_name] = {'idx':no,'caption':title}
                        no = no + 1
        csv_head = ""
        for k,v in sorted(csv_heads.items(),key=lambda x:int(x[1].get('idx'))):
            if csv_head == "":
                csv_head = u'"%s:%s"' % ( k , v.get('caption','') )
            else:
                csv_head = csv_head + u'\t"%s:%s"' % ( k , v.get('caption','') )

        csv_data = u""
        csv_data = csv_head + "\r\n"
        for post in article.posts:
            fields = post.fields
            for k,v in sorted(csv_heads.items(),key=lambda x:int(x[1].get('idx'))):
                if k == "id":
                    csv_data = csv_data + '"%s"' % str(post.id) + "\t"
                elif k == "slug":
                    csv_data = csv_data + '"%s"' % post.slug+ "\t"
                elif k == "title":
                    csv_data = csv_data + '"%s"' % post.title+ "\t"
                elif k == "header":
                    csv_data = csv_data + '"%s"' % post.header+ "\t"
                elif k == "lead":
                    csv_data = csv_data + '"%s"' % post.lead+ "\t"
                elif k == "description":
                    csv_data = csv_data + '"%s"' % post.description+ "\t"
                else:
                    if fields :
                        txt = fields.get("txt_post_%s_%s"%(str(post.id),k),"")
                        try:
                            csv_data = csv_data + '"%s"' % txt.get('string','') + "\t"
                        except:
                            pass
            csv_data = csv_data + "\r\n"
        return csv_head,csv_data


    def GET( self , prefix ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        dic.close()

        article = Articles.select(Articles.q.prefix == prefix).getOne(default=None)
        if not article :
            return web.notfound()

        csv_head , csv_data = self.MakeCSVData( article )

        csv_conv = ""

        return render.articles_trans(     
                                cms = self.cms,
                                scfg = scfg, 
                                mode = 'view',
                                prefix = prefix,
                                article = article,
                                csv_head = csv_head,
                                csv_data = csv_data,
                                csv_conv = csv_conv,
        )


    def POST( self , prefix ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        dic.close()

        article = Articles.select(Articles.q.prefix == prefix).getOne(default=None)
        if not article :
            return web.notfound()

       
        i = web.input()

        csv_head = u""
        csv_data = u""
        if i.has_key("IMPORT_CSV"):
            csv = i.IMPORT_CSV
            lines = csv.split("\r\n")

            hd = lines[0].split("\t")
            head = []
            for h in hd:
                txt = re.search('^"(.*)"$',h)
                if txt :
                    names = txt.group(1).split(":")
                    head.append( names[0] )

            dic = {}
            for l in lines[1:len(lines)]:
                flds = l.split("\t")
                n = 0
                id = ""
                fld = {}
                for f in flds:
                    txt = re.search('^"(.*)"$',f)
                    name = head[n]
                    if txt :
                        if name == 'id':
                            id = txt.group(1)
                        else:
                            fld[name] = txt.group(1)
                    n = n + 1
                dic["id__%s" % id] = fld
            
            csv_conv = dic

        for k,v in csv_conv.items():
            id = k.replace('id__','')
            if id != "":
                id = int(id)
            else:
                continue
            post = Posts.select(Posts.q.id == id ).getOne(default=None)
            if not post :
                continue
            post.slug = v.get('slug') 
            post.title = v.get('title')
            post.description = v.get('description') 
            #post.date = datetime.strptime(i.DATE + " 00:00:00", '%Y-%m-%d %H:%M:%S')
            #post.password = i.PASSWORD
            post.updated = datetime.now() 
            post.syncUpdate()
    
        csv_head , csv_data = self.MakeCSVData( article )
        csv_conv = ""

        return render.articles_trans(     
                                cms = self.cms,
                                scfg = scfg, 
                                mode = 'view',
                                prefix = prefix,
                                article = article,
                                csv_head = csv_head,
                                csv_data = csv_data,
                                csv_conv = csv_conv,
        )



